<?php
namespace app\model;

class Reminder extends BaseModel
{
    // 设置表名
    protected $name = 'reminders';
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    
    // 时间字段转换
    protected $type = [
        'created_at' => 'integer',
        'updated_at' => 'integer',
        'delete_time' => 'integer',
        'due_date' => 'datetime',  // 使用 datetime 类型而不是 timestamp
        'recurrence_end_date' => 'datetime'  // 同样使用 datetime 类型
    ];

    // 追加属性
    protected $append = [
        'status'
    ];

    // 获取提醒状态
    public function getStatusAttr()
    {
        if ($this->is_finished) {
            return 'finished';
        }
        if ($this->is_disabled) {
            return 'disabled';
        }
        if ($this->is_completed) {
            return 'completed';
        }
        return 'active';
    }

    // 关联用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // 自动生成操作密钥
    public static function onBeforeInsert($model)
    {
        if (empty($model->operation_key)) {
            // 使用随机字符串和用户ID生成密钥
            $model->operation_key = md5(uniqid($model->user_id, true));
        }
    }

    /**
     * 关联项目
     */
    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    /**
     * 记录AI辅助历史
     */
    public function recordAiHistory($action, $content)
    {
        $history = $this->ai_history ? json_decode($this->ai_history, true) : [];
        $history[] = [
            'time' => date('Y-m-d H:i:s'),
            'action' => $action,
            'content' => $content
        ];
        $this->ai_history = json_encode($history, JSON_UNESCAPED_UNICODE);
        $this->save();
    }

    /**
     * 获取AI辅助历史
     */
    public function getAiHistoryArray()
    {
        return $this->ai_history ? json_decode($this->ai_history, true) : [];
    }
} 